package com.smedi.ismedi.authoritymanagement.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smedi.ismedi.authoritymanagement.core.domain.aggregatemodel.RolePermissionDetail;
import com.smedi.ismedi.authoritymanagement.core.domain.aggregatemodel.TermPage;
import com.smedi.ismedi.authoritymanagement.core.domain.repository.RolePermissionDetailRepository;
import com.smedi.ismedi.authoritymanagement.core.port.adapter.persistence.model.RolePermissionDetailEntity;
import com.smedi.ismedi.authoritymanagement.core.port.adapter.persistence.model.TermPageEntity;
import com.smedi.ismedi.authoritymanagement.core.port.adapter.persistence.mybatis.mapper.RolePermissionDetailMapper;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.List;

@Slf4j
@Repository
@AllArgsConstructor
public class RolePermissionDetailRepositoryImpl extends ServiceImpl<RolePermissionDetailMapper, RolePermissionDetailEntity> implements RolePermissionDetailRepository, IService<RolePermissionDetailEntity> {
    private final DozerUtil dozerUtil;

    @Override
    public List<RolePermissionDetail> selectAllByRootCodeAndRoleId(String rootCode, Long roleId) {
        QueryWrapper<RolePermissionDetailEntity> wrapper = new QueryWrapper();
        wrapper.eq("root_code", rootCode)
                .eq("role_id", roleId)
                .orderByAsc("id");

        return dozerUtil.convertor(this.getBaseMapper().selectList(wrapper), RolePermissionDetail.class);
    }

    @Override
    public List<RolePermissionDetail> selectAllByRootCodeAndRoleIds(String rootCode, List<Long> roleIds) {
        QueryWrapper<RolePermissionDetailEntity> wrapper = new QueryWrapper();

        wrapper.eq("root_code", rootCode);
        if(null!=roleIds&&!roleIds.isEmpty()){
            wrapper.in("role_id", roleIds);
        }
        wrapper.orderByAsc("id");

        return dozerUtil.convertor(this.getBaseMapper().selectList(wrapper), RolePermissionDetail.class);
    }

    @Override
    public void deleteAllByRootCodeAndRoleId(String rootCode, Long roleId) {
        QueryWrapper<RolePermissionDetailEntity> wrapper = new QueryWrapper();
        wrapper.eq("root_code", rootCode)
                .eq("role_id", roleId);

        this.getBaseMapper().delete(wrapper);
    }

    @Override
    public RolePermissionDetail doInsert(RolePermissionDetail rolePermissionDetail) {
        RolePermissionDetailEntity row = dozerUtil.convertor(rolePermissionDetail, RolePermissionDetailEntity.class);
        this.getBaseMapper().insert(row);
        return (RolePermissionDetail) dozerUtil.convertor(row, RolePermissionDetail.class);
    }
}
